<template>
  <div :id="id" :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    dataObj: Object
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    dataObj (val) {
      this.chart && this.chart.setOption({
        xAxis: {
          data: val.xdata
        },
        series: val.series
      }, {
        replaceMerge: 'series'
      })
    }

  },
  mounted () {
    this.initChart()
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart () {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let html = ''
            params.forEach(it => {
              html +=
              it.marker +
              it.seriesName + '：' +
              (it.seriesName.includes('率') ? it.value + '%' : it.value) +
                '<br>'
            })
            return html
          }
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        legend: {
          type: 'scroll',
          bottom: 10
          // selected: legend.reduce((obj, label) => {
          //   obj[label] = selectLegend.includes(label)
          //   return obj
          // }, {})
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value'
        }
      })
      // this.chart.on('legendselectchanged', function (event) {
      //   var isSelected = event.selected[event.name] // 获取当前图例的选中状态
      //   console.log(event.name + ' is ' + (isSelected ? 'selected' : 'unselected'))
      //   // 在这里可以根据event.name和isSelected来执行你想要的操作
      // })
    }
  }
}
</script>
